/**
 * Copyright 2009 Emory University
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated  documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 * and/or sell copies of the Software, and to permit persons to whom the 
 * Software is furnished to do so, subject to the following conditions: The 
 * above copyright notice and this permission notice shall be included in all 
 * copies or substantial portions of the Software. 
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */
package com.markgrand.structuredSql

/**
 * This trait is used to append a REFERENCES clause to a StringBuilder. A 
 * references clause is used for REFERENCES column constraints and for FOREIGN
 * KEY table constraints.  
 * 
 * @param constraintName
 *      An optional name for the column constraint.
 */
private[structuredSql] trait References extends SQLIdentifier {
  /**
   * The name of the referenced table.
   */
  val refTable : TableName
  
  /**
   * The names of references columns. If no columns are explicitly named then
   * this should have zero length. 
   */
  val refColumnNames:Seq[String]
  
  /**
   * The rule to use for null in foreign key values.
   */
  val matchType:Option[ForeignKeyMatch.Value]
  
  /**
   * The action to take when a foreign key value is altered by an update.
   */
  val updateAction:Option[ForeignKeyAction.Value]
  
  /**
   * The action to take when row that is the target of a foreign key reference 
   * is deleted.
   */
  val deleteAction:Option[ForeignKeyAction.Value]
  
  def appendReferences(builder:StringBuilder) {
    builder.append("REFERENCES ")
    refTable.append(builder)
    if (refColumnNames.length > 0){
      builder.append("(")
      appendIdentifierSeq(refColumnNames, builder)
      builder.append(")")
    }
    if (matchType.isDefined){
      builder.append(" ")
      builder.append(matchType.get.toString)
    }
    if (updateAction.isDefined){
      builder.append(" ON UPDATE ")
      builder.append(updateAction.get.toString)
    }
    if (deleteAction.isDefined){
      builder.append(" ON DELETE ")
      builder.append(deleteAction.get.toString)
    }
  }
}
